const Router = require("koa-router");
const login = new Router();
const bodyParser = require("koa-bodyparser");
const db = require("../utils/db");
const jwt = require("jsonwebtoken");
login.use(bodyParser());

login.post("/register", async (ctx) => {
  let myaccount = ctx.request.body.account;
  let mypwd = ctx.request.body.pwd;
  //   设置sql语句查询数据库里是否有账号，同时返回结果
  let sql = `SELECT * FROM users WHERE account='${myaccount}'`;
  let res = await new Promise((resolve, reject) => {
    //   数据库查询操作
    return db.query(sql, (err, data) => {
      if (err) throw err;
      if (data.length > 0) {
        resolve(data);
      } else {
        resolve(false);
      }
    });
  });
  if (res) {
    // 找到账号了
    if (res[0].pwd == mypwd) {
      // 账号密码正确，返回token
      ctx.body = {
        token: result[0],
        msg: "登录成功",
        account: myaccount,
      };
    } else {
      // 密码错误
      ctx.body = {
        msg: "密码错误",
        account: myaccount,
      };
    }
  } else {
    // 找不到对应的账号，直接插入一个
    let res1 = await new Promise((resolve, reject) => {
      const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, "secret", {
        expiresIn: 3600,
      });
      return db.query(
        `INSERT INTO users (account, pwd, token) values ('${myaccount}', '${mypwd}', '${token}')`,
        (error, datas) => {
          if (error) throw error;
          let obj = {
            token,
            msg: "success!!",
            account: myaccount,
          };
          resolve(obj);
        }
      );
    });
    //生成token
    if (res1) {
      ctx.body = res1;
    }
  }
});
module.exports = login;
